package com.seecen.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seecen.pojo.dto.UserDto;
import com.seecen.pojo.entity.User;
import com.seecen.service.UserService;
import com.seecen.mapper.UserMapper;
import com.seecen.utils.JwtHelper;
import com.seecen.utils.MD5Utils;
import com.seecen.utils.Result;
import com.seecen.utils.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;

/**
* @author 酒醉
* @description 针对表【sys_user】的数据库操作Service实现
* @createDate 2025-10-16 14:27:30
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    private UserMapper userMapper;


    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public Result login(UserDto userDto) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,userDto.getUsername());
        User user = userMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNull(user)){
            return Result.build(null, ResultCode.USERNAME_ERROR);
        }

        if (!ObjectUtil.isEmpty(userDto.getPassword())&&MD5Utils.encrypt(userDto.getPassword()).
        equals(user.getPassword())){
            String token = jwtHelper.createToken(Long.valueOf(user.getUserId()));
            // 修复：确保token正确包装在返回结果中
            HashMap<String, String> data = new HashMap<>();
            data.put("token",token);
            return Result.ok(data);
        }
        return Result.build(null,ResultCode.PASSWORD_ERROR);
    }

    @Override
    public Result register(User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,user.getUsername());
        User selectOne = userMapper.selectOne(queryWrapper);
        if (!ObjectUtil.isNull(selectOne)){
            return Result.build(null, ResultCode.USERNAME_USED);
        }
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setPassword(MD5Utils.encrypt(user.getPassword()));
        userMapper.insert(user);
        return Result.ok(null);
    }

    @Override
    public Result getUser(String token) {
        boolean expiration = jwtHelper.isExpiration(token);
        if (expiration){
            return Result.build(null,ResultCode.NOTLOGIN);
        }
        Long userId = jwtHelper.getUserId(token);
        User user = userMapper.selectById(userId);
        user.setPassword(null);
        HashMap<String, Object> data = new HashMap<>();
        data.put("user",user);
        return Result.ok(user);
    }

}




